#include "gm_handle_mgr.h"
#include "gm_handle.h"
#include <string.h>
gm_handle_mgr::gm_handle_mgr(void)
{
}

gm_handle_mgr::~gm_handle_mgr(void)
{
}


void gm_handle_mgr::clear()
{
	mk_node* pHead = _sc_handle_list.get_head();
	while (pHead != NULL)
	{
		mk_node *node = pHead;
		gm_handle * pHandle = (gm_handle *)node->get_data();
		delete pHandle;
		pHead = node->get_next_node();
	}
	_sc_handle_list.remove_all();
	return ;
}

int gm_handle_mgr::add_handle(HANDLE handle)
{
	return _sc_handle_list.add(handle);
}

ULONG gm_handle_mgr::remove_handle(HANDLE handle)
{
	mk_node* pHead = _sc_handle_list.get_head();
	if(pHead == NULL) return 0;
	gm_handle *pkey = (gm_handle *)pHead->get_data();

	if(pkey->get_handle() == handle)
	{
		delete pkey;
		_sc_handle_list.remove(pkey);
		return SAR_OK;
	}

	mk_node* pNode = pHead->get_next_node();

	while(pNode != NULL)
	{
		pkey = (gm_handle *)pNode->get_data();
		if(pkey->get_handle()  == handle)
		{
			delete pkey;
			_sc_handle_list.remove(pkey);
			return SAR_OK;
		}
		pNode = pNode->get_next_node();
	}

	return SAR_FAIL;
}

gm_handle* gm_handle_mgr::get_first_handle()
{
	_curr_pos = _sc_handle_list.get_head();
	if(_curr_pos == NULL)
	{
		return NULL;
	}
	return (gm_handle *)_curr_pos->get_data();
}

gm_handle* gm_handle_mgr::get_next_handle()
{
	if(_curr_pos == NULL)
	{
		_curr_pos =  _sc_handle_list.get_head();
	}

	if(_curr_pos == NULL)
	{
		return NULL;
	}

	_curr_pos = _curr_pos->get_next_node();
	if(_curr_pos == NULL)
	{
		return NULL;
	}

	return (gm_handle *)_curr_pos->get_data();
}